﻿Public Class FrmValidacionRefactorizado

    Private Sub txtNombre_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles txtNombre.Validating
        e.Cancel = ValidateTextControl(txtNombre, AddressOf IsNombreValid, "Sólo letras")
    End Sub

    Private Sub txtNroDoc_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles txtNroDoc.Validating
        e.Cancel = ValidateTextControl(txtNroDoc, AddressOf IsNroDocValid, "Sólo números")
    End Sub

    Private Sub txtApellido_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles txtApellido.Validating
        e.Cancel = ValidateTextControl(txtApellido, AddressOf IsApellidoValid, "Sólo letras")
    End Sub

    Private Sub btnAceptar_Click(sender As System.Object, e As System.EventArgs) Handles btnAceptar.Click
        If IsFormValid() Then
            MessageBox.Show("Aceptar")
            Me.Close()
        Else
            MessageBox.Show("No es válido")
        End If
    End Sub

    Private Function IsNombreValid() As Boolean
        Return Validador.IsOnlyText(txtNombre.Text)
    End Function

    Private Function IsApellidoValid() As Boolean
        Return Validador.IsOnlyText(txtApellido.Text)
    End Function

    Private Function IsNroDocValid() As Boolean
        Return Validador.IsOnlyNumber(txtNroDoc.Text)
    End Function

    Private Function IsFormValid() As Boolean
        Return IsNombreValid() AndAlso IsApellidoValid() AndAlso IsNroDocValid()
    End Function

    Private Sub btnCancelar_Click(sender As System.Object, e As System.EventArgs) Handles btnCancelar.Click
        Me.Close()
    End Sub

    Private Function ValidateTextControl(ByVal textControl As TextBox, ByVal validateFunction As Func(Of Boolean), ByVal errorMessage As String) As Boolean
        If Not validateFunction() Then
            errorProvider.SetError(textControl, errorMessage)
            Return True
        Else
            errorProvider.SetError(textControl, Nothing)
        End If
        Return False
    End Function
End Class